const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('../config/constants')

const auth = async (req, res, next) => {
  try {
    const token = req.header('Authorization').replace('Bearer ', '')
    const decoded = jwt.verify(token, JWT_SECRET)
    req.user = decoded
    next()
  } catch (error) {
    res.status(401).json({
      success: false,
      message: '请先登录'
    })
  }
}

// 管理员权限验证
const adminAuth = async (req, res, next) => {
  try {
    const token = req.header('Authorization').replace('Bearer ', '')
    const decoded = jwt.verify(token, JWT_SECRET)
    
    if (!decoded.isAdmin) {
      throw new Error()
    }
    
    req.user = decoded
    next()
  } catch (error) {
    res.status(403).json({
      success: false,
      message: '无权限访问'
    })
  }
}

module.exports = { auth, adminAuth } 